//
//  SelectPhotosView.m
//  PigMarket
//
//  Created by Felix on 2019/3/27.
//  Copyright © 2019 felix.pigmarket.oc. All rights reserved.
//

#import "SelectPhotosView.h"
#import "SelectPhotoCell.h"
#import "TZImagePickerController.h"

@interface SelectPhotosView ()<UICollectionViewDataSource,UICollectionViewDelegate,TZImagePickerControllerDelegate>

/**
 currentPhotos
 */
@property (nonatomic , strong) NSMutableArray *currentPhotos;
/**
 currentAssets
 */
@property (nonatomic , strong) NSMutableArray *currentAssets;

@property (nonatomic, assign) NSInteger maxPhotoCount;

@end

@implementation SelectPhotosView

#pragma mark - init method
- (instancetype)init
{
    self = [super init];
    if (self) {
        self.maxPhotoCount = 2;
        [self initView];
        [self initLayout];
    }
    return self;
}
- (instancetype)initSelectPhotosView:(NSInteger)maxPhotoCount {
    self = [super init];
    if (self) {
        self.maxPhotoCount = maxPhotoCount;
        [self initView];
        [self initLayout];
    }
    return self;
}

- (void)initView {
    // 添加子控件
    [self addSubview:self.photoCollectionView];
}

- (void)initLayout {
    // 布局子控件
    [self.photoCollectionView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.left.right.bottom.mas_equalTo(0);
        make.edges.mas_equalTo(0);
    }];
}

#pragma mark - delegate
#pragma mark UICollectionViewDelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.currentPhotos.count >= self.maxPhotoCount) {
        return self.currentPhotos.count;
    }
    return self.currentPhotos.count + 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    SelectPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"SelectPhotoCellID" forIndexPath:indexPath];
    if (indexPath.item == self.currentPhotos.count) {
        cell.imageView.image = [UIImage imageNamed:@"common_addphoto"];
        cell.deleteBtn.hidden = YES;
    } else {
        cell.imageView.image = self.currentPhotos[indexPath.item];
    }
    cell.deleteBtn.tag = indexPath.item;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    return cell;
}
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.item == self.currentPhotos.count) {
        @weakify(self);
        [[AlertAction sharedInstance] showAlertSheetWithTitle:nil message:nil itemsArr:@[@"拍照",@"相册选择"] selectItemBlock:^(NSString *selectItem) {
            @strongify(self);
            if ([selectItem isEqualToString:@"拍照"]) {
                [self takePhoto];
            } else if ([selectItem isEqualToString:@"相册选择"]) {
                [self photoAlbum];
            }
        }];
        
    } else {
//        SelectPhotoCell *cell = (SelectPhotoCell *)[self.photoCollectionView cellForItemAtIndexPath:indexPath];
//        if (cell.isShaking) {
//            cell.isShaking = NO;
//            cell.deleteBtn.hidden = YES;
//            [self endShake:cell];
//        } else {
//            TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithSelectedAssets:_currentAssets selectedPhotos:_currentPhotos index:indexPath.item];
//            imagePickerVc.maxImagesCount = MaxPhotoCount;
//            //            imagePickerVc.allowPickingGif = self.allowPickingGifSwitch.isOn;
//            //            imagePickerVc.allowPickingOriginalPhoto = self.allowPickingOriginalPhotoSwitch.isOn;
//            //            imagePickerVc.allowPickingMultipleVideo = self.allowPickingMuitlpleVideoSwitch.isOn;
//            //            imagePickerVc.showSelectedIndex = self.showSelectedIndexSwitch.isOn;
//            imagePickerVc.isSelectOriginalPhoto = self.isSelectOriginalPhoto;
//            [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
//                self->_currentPhotos = [NSMutableArray arrayWithArray:photos];
//                self->_currentAssets = [NSMutableArray arrayWithArray:assets];
//                self->_isSelectOriginalPhoto = isSelectOriginalPhoto;
//                [self->_photoCollectionView reloadData];
//                //                self->_photoCollectionView.contentSize = CGSizeMake(0, ((self->_currentPhotos.count + 2) / 3 ) * (4 + self->_itemWH));
//            }];
//            [self presentViewController:imagePickerVc animated:YES completion:nil];
//        }
    }
}

#pragma mark - private method
- (void)deleteBtnTapped:(UIButton *)btn {
    if ([self collectionView:self.photoCollectionView numberOfItemsInSection:0] <= _currentPhotos.count) {
        [_currentPhotos removeObjectAtIndex:btn.tag];
        [_currentAssets removeObjectAtIndex:btn.tag];
        [self.photoCollectionView reloadData];
        return;
    }
    
    [_currentPhotos removeObjectAtIndex:btn.tag];
    [_currentAssets removeObjectAtIndex:btn.tag];
    [_photoCollectionView performBatchUpdates:^{
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:btn.tag inSection:0];
        [self->_photoCollectionView deleteItemsAtIndexPaths:@[indexPath]];
    } completion:^(BOOL finished) {
        [self->_photoCollectionView reloadData];
    }];
}
/** 拍照 */
- (void)takePhoto {
    if (self.takePhotoBlock) {
        self.takePhotoBlock();
    }
}
/** 相册 */
- (void)photoAlbum {
    if (self.photoAlbumBlock) {
        self.photoAlbumBlock();
    }
//    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:6 columnNumber:4 delegate:self pushPhotoPickerVc:YES];
//    imagePickerVc.allowTakeVideo = NO;
//    imagePickerVc.selectedAssets = self.currentAssets; // 目前已经选中的图片数组
//    [self presentViewController:imagePickerVc animated:YES completion:nil];
}

#pragma mark - getter and setter

- (UICollectionView *)photoCollectionView {
    if (!_photoCollectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake(74, 74);
        flowLayout.minimumLineSpacing = 5;
        flowLayout.minimumInteritemSpacing = 5;
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        _photoCollectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        // 注册CollectionView的Cell
        [_photoCollectionView registerClass:[SelectPhotoCell class] forCellWithReuseIdentifier:@"SelectPhotoCellID"];
        _photoCollectionView.delegate = self;
        _photoCollectionView.dataSource = self;
//        _photoCollectionView.backgroundColor = [UIColor colorWithHexString:@"#ffffff"];
    }
    return _photoCollectionView;
}
- (NSMutableArray *)currentPhotos {
    if (!_currentPhotos) {
        _currentPhotos = [NSMutableArray array];
    }
    return _currentPhotos;
}
- (NSMutableArray *)currentAssets {
    if (!_currentAssets) {
        _currentAssets = [NSMutableArray array];
    }
    return _currentAssets;
}

@end

